# recv.tcl - stuff for handling data from server
# 
# CONTENTS:
#	recv {chid frname}
#		Gets data from $chid, and calls a handle to handle it. It is
#		[recv] that calls the modules' functions from $RECV_LISTEN.

set CHAN ""
set NS {}


proc recv {chid frname} {
	global n_conns
	global mes
	global VERSION
	global NS
	global CHAN
	global NAMESLOCK
	
	global RECV_LISTEN
	
	set me $mes($chid)
	set parent $n_conns.$frname
	gets $chid line
	puts "$chid: $line"
	set tstamp [clock format [clock seconds] -format "%T"]
	
	if [eof $chid] {
		close $chid
		errmsg $parent.console "Lost connection to server"
		closealltabs $parent
	}
	
	if [regexp {PING :(.+)} $line -> pingcode] {
		raw $chid "PONG :$pingcode"
	}
	
	if [regexp {ERROR :(.+)} $line -> msg] {
		errmsg $parent.console "$msg\n"
	}
	
	switch -- "[lindex [split $line] 1]" {
		001 - 002 - 003 - 376 - 375 {
			regexp {:[^ ]+ [^ ]+ [^ ]+ :(.+)} $line -> msg
			infomsg $parent.console "$msg\n"
		}
		
		005 {
			regexp {:[^ ]+ 005 [^ ]+ (.+)} $line -> msg
			infomsg $parent.console "$msg\n"
		}
		
		372 {
			regexp {:[^ ]+ [^ ]+ [^ ]+ :(.+)} $line -> msg
			$parent.console.mainbox.output insert end "\[$tstamp\] $msg\n"
		}
		
		471 {
			regexp {:[^ ]+ [^ ]+ [^ ]+ ([^ ]+) :.+ \(([^\)]+)\)} $line -> channel reason
			warning $parent.console "Can't join $channel, channel is full\n"
		}
		
		473 {
			regexp {:[^ ]+ [^ ]+ [^ ]+ ([^ ]+) :.+ \(([^\)]+)\)} $line -> channel reason
			warning $parent.console "Can't join $channel, channel is invite-only\n"
		}
		
		474 {
			regexp {:[^ ]+ [^ ]+ [^ ]+ ([^ ]+) :.+ \(([^\)]+)\)} $line -> channel reason
			warning $parent.console "Can't join $channel, you are banned\n"
		}
		
		519 - 520 {
			regexp {:[^ ]+ [^ ]+ [^ ]+ :.+ \(([^\)]+)\)} $line -> reason
			warning $parent.console "$reason\n"
		}
		
		477 {
			# 477 - Can't join because of +R
			regexp {:[^ ]+ [^ ]+ [^ ]+ ([^ ]+) :(.+)} $line -> channel msg
			warning $parent.console "$channel: $msg\n"
		}
		
		478 {
			# 478 - Banlist is full
			regexp {:[^ ]+ [^ ]+ ([^ ]+) [^ ]+ :(.+)} $line -> channel msg
			
			set chanlabel [string tolower [string map { "#" "" } $channel]]
			errmsg $parent.$chanlabel "Ban list is full"
		}
		
		default {
			# Here is a fallback that calls functions
			# contained in modules, in case we've got
			# a handler there.
			foreach name [array names RECV_LISTEN] {
				if { [string tolower $name] == \
					[string tolower [lindex [split $line] 1]]} {
					eval "$RECV_LISTEN($name) \$chid \$line \$parent \$me"
				}
			}
		}
	}
}
